package com.bdcom.autotest.interaction.db;

import com.bdcom.autotest.telnet.util.ping.OSinfo;
import com.bdcom.autotest.util.Prop;
import com.bdcom.autotest.util.RunScriptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

public class CheckMysql {


        private static final Logger logger = LoggerFactory.getLogger(CheckMysql.class);

        public boolean startMySQL() throws Exception {
            try {
                // 判断是否已经启动mysql 实例
                Socket socket = new Socket(Prop.MYSQL_HOST, Prop.MYSQL_PORT);
                socket.close();
                return true;
            } catch (Exception e) {
                logger.info("No Mysql running! NMS will start Mysql!");
            }
            try {
                RunScriptUtil.runScript(Prop.binDir+ File.separator, "startMySQL");
                boolean checkMysql = checkMysql();
                return checkMysql;
            } catch (Exception e) {
                logger.error("", e);
                throw new Exception(e.getMessage());
            }

        }

        private boolean checkMysql() {
            Socket socket = null;
            int count = 0;
            do {
                if (count >= 40)
                    break;
                try {
                    socket = new Socket(Prop.MYSQL_HOST, Prop.MYSQL_PORT);
                    socket.close();
                    return true;
                } catch (Exception es) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                    }
                    count++;
                }
            } while (true);

            return false;
        }

        public void stopMysql() throws IOException {
            try {
                if (OSinfo.isWindows()) {
                    RunScriptUtil.runScript(Prop.binDir+File.separator, "stopMySQL");
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }


}
